import { notification } from 'antd';
import { UPLOAD } from './../../pages/data/devices/enum';
import { queryTemple } from '@/services/devices';
import { importFile } from '@/pages/data/devices/service';

export default {
  namespace: 'devices',

  state: {
    key: "",
    temple: {},
    show: false
  },

  effects: {
    *handleKey({ payload }, { put, select }) {
      const preKey = yield select(state => state.devices.key);
      yield put({ type: `${preKey}/setCond`, payload: {} })
      yield put({ type: 'setKey', payload })
      yield put({ type: 'setSubKey', payload: null })
    },
    *initCond(_, { put }) {
      yield put({ type: 'setCond', payload: {} });
      yield put({ type: 'queryPage' })
    },
    *handleDetail({ payload }, { call, put }) {
      yield put({ type: 'setSub', payload })
    },
    *queryTemple({ payload }, { call, put }) {

      const { list } = yield call(queryTemple, { name: UPLOAD[payload.type].name });
      const ans = {
        ...(Array.isArray(list) && list[0] ? list[0] : {}),
        name: UPLOAD[payload.type].name,
        ...payload
      }
      yield put({ 
        type: 'setTemple', 
        payload: ans
      });
      yield put({ type: 'handleShow', payload: true})
    },
    *importFile({ payload }, { call, put, select }) {
      const temple = yield select(state => state.devices.temple)
      const { type, parentId } = temple;
      const tail = UPLOAD[type].tail;
      yield put({ type: 'handleShow', payload: false})
      const msg = yield call(importFile, { tail, parentId, ...payload })
      yield put({ type: `${type}/queryPage`, payload: { parentId, pageNum: 1, pageSize: 10 } })
      msg && notification.success({
        message: '保存成功',
        description: msg
      });
    }
  },

  reducers: {
    setKey(state, action) {
      return {
        ...state,
        key: action.payload
      }
    },
    setSubKey(state, action) {
      return {
        ...state,
        subKey: action.payload
      }
    },
    setTemple(state, action) {
      return {
        ...state,
        temple: action.payload
      }
    },
    handleShow(state, action) {
      return {
        ...state,
        show: action.payload
      }
    }
  }
}
